package com.ph.order.api.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.customenum.SmsCodeType;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.common.util.rsa.MD5;
import com.ph.shopping.common.util.transform.MoneyTransUtil;
import com.ph.shopping.facade.member.dto.MemberCardInfoDto;
import com.ph.shopping.facade.member.dto.PayPasswordDto;
import com.ph.shopping.facade.member.entity.TradersPassword;
import com.ph.shopping.facade.member.service.IMemberCardService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.member.service.ISmsCodeSendService;
import com.ph.shopping.facade.merchant.entity.UserBalance;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.permission.vo.SessionRoleVo;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.score.service.IScoreService;
import com.ph.shopping.facade.score.vo.MemberScoreVo2;

import cm.ph.shopping.facade.order.service.IUnLineOrerService;
import cm.ph.shopping.facade.order.vo.PhOrderUnlineVo;
import cm.ph.shopping.facade.order.vo.QueryMerchantOrderTakeVo;
import cm.ph.shopping.facade.order.entity.PhOrderUnline;

/**
 * @项目：phshopping-api-platform
 *
 * @描述：商户线下订单 和 商户的提货订单
 *
 * @作者： huangdd
 *
 * @创建时间：2017年3月29日
 *
 * @Copyright @2017 by huangdd
 */
@Controller
@RequestMapping("api/merchantUnLineOrder")
public class MerchantUnLineOrderController extends BaseController {
	
	@Reference(version="1.0.0")
	IUnLineOrerService IUnLineOrerService;
	
    @Reference(version = "1.0.0")
    private ISmsCodeSendService iSmsCodeSendService;
    
	@Reference(version="1.0.0")
	IMemberCardService  IMemberCardService;
	
	@Reference(version="1.0.0")
	IMerchantService iMerchantService;
	
	@Reference(version="1.0.0")
	IMemberService iMemberService;
	
	@Reference(version="1.0.0")
	IScoreService iScoreService;
	/**
	 * 跳转线下订单list页面
	 * @return
	 */
	@RequestMapping(value="/unLineOrderPage",method=RequestMethod.GET)
	public String getMerchantList(){
		return "/order/unLineOrder/unLineOrderList";
	}
	/**
	 * 获取商户线下订单List(代理 管理员都要来调用此接口)
	 * @return
	 */
	@RequestMapping(value="/unLineOrderList",method=RequestMethod.GET)
	@ResponseBody
	public Object getMerchantUnLineOrderVoList(@ModelAttribute PhOrderUnlineVo phOrderUnlineVo,PageBean pagebean){
		try{
			Long agentId = null;
			SessionUserVo sessionUserVo = getLoginUser();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				if("ADMIN".equals(roleEnum.name())){
					phOrderUnlineVo.setMerchantId(null);
				}else if("CITY_AGENT".equals(roleEnum.name()) || "COUNTY_AGENT".equals(roleEnum.name()) || "COMMUNITY_AGENT".equals(roleEnum.name())){
					phOrderUnlineVo.setAgentId(getLoginUser().getId());
				}else{
					phOrderUnlineVo.setMerchantId(getLoginUser().getId());//重session中获取id
				}
			}
			return IUnLineOrerService.getUnLineOrderVoList(phOrderUnlineVo,pagebean);
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取线下订单列表异常");
			return getResult(ResultEnum.NO_UNLINEORDERDATA_EXCEPTION);
		}
	}
	/**
	 * 跳转创建线下订单页面
	 * @return
	 */
	@RequestMapping(value="/establishUnLineOrderPage",method=RequestMethod.GET)
	public String  examineMerchantList(HttpServletRequest request){
		request.setAttribute("orderNO", CreateOrderUtil.createOrderCode(OrderBizCode.MEMBER_UNLINEORDER));
		return "/order/unLineOrder/establishUnLineOrder";
	}
	
	/**
	 * 创建线下订单
	 * @param merchant
	 * @return
	 */
	@RequestMapping(value="/addUnLineOrder",method=RequestMethod.POST)
	@ResponseBody
	public Object addUnLineOrder(PhOrderUnline phOrderUnline,String verificationCode,String payPassWord){
		Result result = getResult(ResultEnum.SUCCESS);
		try{
			phOrderUnline.setMerchantId(getLoginUser().getId());//当前商户的id
			//判断会员卡号相关
			Result memberCardInfoByCode = IMemberCardService.getMemberCardInfoByInnerCode(phOrderUnline.getMemberCard());
			logger.info(" Result ={}",JSON.toJSON(memberCardInfoByCode));
			if(!memberCardInfoByCode.getCode().equals("200")){
				return getResult(ResultEnum.NO_MEMBERCARD_EMPTY);//无此会员卡数据
			}
			MemberCardInfoDto emberCardInfoDto = (MemberCardInfoDto)memberCardInfoByCode.getData();
			phOrderUnline.setMemberId(emberCardInfoDto.getId());
			
			if(phOrderUnline.getPayTpe()==1){//现金支付
				//判断该商户的余额和此账户是否存在
				UserBalance userBalance = new UserBalance();
				userBalance.setManageId(phOrderUnline.getMerchantId());
				Result userBalance2 = iMerchantService.getUserBalance(userBalance);
				if(!userBalance2.getCode().equals("200")){//无此账户
					return userBalance2;
				}
				if((((UserBalance)userBalance2.getData()).getBalance()+10000000) < MoneyTransUtil.transMultiDouble(phOrderUnline.getOrderMoney())){//余额不足
					return getResult(ResultEnum.NOENOUGH_MONEY_EXCEPTION);
				}
				
				//判断商户密码
				PayPasswordDto dto = new PayPasswordDto();
				dto.setCustomerType(2);//平台支付密码
				dto.setRelatedId(phOrderUnline.getMerchantId());//用户id
				result = iMemberService.getPayPwdInfo(dto);
				if(!result.getCode().equals("200")){
					logger.error("获取商户支付密码异常"); 
					return getResult(ResultEnum.NO_MEMBERPAYPASS_EXCEPTION);
				}
				TradersPassword p = (TradersPassword)result.getData();
				String md5Str = MD5.getMD5Str(payPassWord);
				if(!p.getPayPwd().equals(MD5.getMD5Str(payPassWord))){
					logger.error("商户密码不对");
					return getResult(ResultEnum.ERROR_PAYPASSWORD_EXCEPTION);
				}
			}else{
				//判断会员的积分是否充足
			     MemberScoreVo2 memberScore = iScoreService.getMemberScore(phOrderUnline.getMemberId());
			     if(memberScore == null){
			    	 logger.error("没有查询到用户的积分");
			    	 return getResult(ResultEnum.NO_MEMBERSCORCE_EXECEPTION);
			     }
			     if(memberScore.getEnablescore() < phOrderUnline.getOrderMoney()*10000){//积分不足
						return getResult(ResultEnum.NOENOUGH_MEMBER_SCORE_EXCEPTION);
					}
				//验证短信 验证没问题了才发短信
				 result = iSmsCodeSendService.verifySmsCode(((MemberCardInfoDto)memberCardInfoByCode.getData()).getMemberPhone(), SmsCodeType.SCORE_PAY.getCodeType(), verificationCode);
			        if(!result.getCode().equals("200")){
			        	logger.error("短信验证异常");
			        	return getResult(ResultEnum.CHECKBIND_EXCEPTION);
			        }			    
			}
			Result addUnLineOrder = IUnLineOrerService.addUnLineOrder(phOrderUnline);
		}catch (Exception e) {
			e.printStackTrace();
			logger.error("创建线下订单异常:", e.getMessage());
			return getResult(ResultEnum.ADD_MERCHANTUNLINEORDER_EXCEPTION);
		}
		return result;
	}
    /**
     * @param bankCardInfo
     * @return
     * @发送验证码
     */
    @RequestMapping(value = "/sendValidCode", method = RequestMethod.POST)
    @ResponseBody
    public Object sendValidCode(@ModelAttribute PhOrderUnline phOrderUnline) {
    	Result result = getResult(ResultEnum.SUCCESS);
    	try{
	    	//先通过会员卡内码获取会员手机号码
	    	Result memberCardInfoByCode = IMemberCardService.getMemberCardInfoByInnerCode(phOrderUnline.getMemberCard());
			if(!memberCardInfoByCode.getCode().equals("200")){
				logger.error("根据卡号获取会员信息失败");
				return memberCardInfoByCode;
			}
			MemberCardInfoDto emberCardInfoDto = (MemberCardInfoDto)memberCardInfoByCode.getData();
	        return iSmsCodeSendService.sendSmsCodeByNoMsg(emberCardInfoDto.getMemberPhone(), SmsCodeType.SCORE_PAY.getCodeType());
    	}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
    }  
    /**
     * 跳转商户提货订单页面
     * @return
     */
    @RequestMapping(value="/getMerchantTakeOrderPage",method=RequestMethod.GET)
    public String getMerchantTakeOrderPage(){
    	return "/order/orderTake";
    }  
    
    /**
     * 提货订单VOlist
     * @return
     */
	@RequestMapping(value="/getMerchantTakeOrderVoList",method=RequestMethod.GET)
	@ResponseBody
    public Object getMerchantTakeOrderVoList(QueryMerchantOrderTakeVo queryMerchantOrderTakeVo, PageBean pagebean){
    	queryMerchantOrderTakeVo.setMerchantId(getLoginUser().getId());
    	return IUnLineOrerService.getMerchantTakeOrderVoList(queryMerchantOrderTakeVo,pagebean);
    }
}
